//
//  AddAdressViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/9/30.
//  Copyright © 2016年 fatcat. All rights reserved.
//  添加收货地址页面，包括定位功能

import UIKit
import CoreLocation
class AdressAddViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, CLLocationManagerDelegate {

    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    let INFO_KEY_CN = ["地区","详细地址","收件人","联系电话","默认收货地址"]
    let RECEIVER_INPUT_ID = 101
    let PHONE_NO_INPUT_ID = 102
    
    var localAddress: NSMutableArray!
    var currentIndex:Int!
    var currentAddress: NSMutableDictionary!
    
    var tableView: UITableView!
    
    var areaLabel: UILabel!
    var specifyTextField: UITextField!
    var receiverTextField: UITextField!
    var phoneNoTextField: UITextField!
    var defaultAddressSwitch: UISwitch!
    
    var areaSetView: UIControl!
    var areaPicker: UIPickerView!
    var areaConfirmBtn: UIButton!
    
    // 定位用
    var locateBtn: UILabel!
    var locateMan: CLLocationManager!
    var locating = false
    
    var locatePlistInfo: NSArray!
    var pickerPosition = [0,0,0]
    var locateData = ["","",""]
    
    convenience init(addressIndex: Int){
        self.init()
        currentIndex = addressIndex
        if NSFileManager.defaultManager().fileExistsAtPath("\(DOCUMENT_PATH)/address.plist") {
            localAddress = NSMutableArray(contentsOfFile: "\(DOCUMENT_PATH)/address.plist")
        }else{
            localAddress = NSMutableArray()
        }
        if currentIndex >= localAddress.count {
            currentAddress = NSMutableDictionary()
        }else{
            let editItem = localAddress.objectAtIndex(currentIndex) as? NSDictionary
            if editItem != nil{
                currentAddress = NSMutableDictionary(dictionary: editItem!)
                print(currentAddress)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locatePlistInfo = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("address", ofType: "plist")!)
        
        view.backgroundColor = UIColor.whiteColor()
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        tableView.keyboardDismissMode = .OnDrag
        
        title = "编辑地址"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .Plain, target: self, action: #selector(AdressAddViewController.saveAddress))
        
        areaLabel = UILabel(frame: CGRect(x: view.bounds.width*0.4-32, y: 12, width: view.bounds.width*0.6, height: 20))
        areaLabel.text = ""
        areaLabel.textAlignment = .Right
        
        specifyTextField = UITextField(frame: CGRect(x: 16, y: 36, width: view.bounds.width-32, height: 20))
        specifyTextField.placeholder = "请填写地址以确保配送工作"
        
        receiverTextField = UITextField(frame: CGRect(x: view.bounds.width/2, y: 12, width: (view.bounds.width-28)/2, height: 20))
        receiverTextField.placeholder = "你的名字"
        receiverTextField.textAlignment = .Right
        receiverTextField.tag = RECEIVER_INPUT_ID
        receiverTextField.addTarget(self, action: #selector(AdressAddViewController.scrollUpTextField(_:)), forControlEvents: .EditingDidBegin)
        
        phoneNoTextField = UITextField(frame: CGRect(x: view.bounds.width/2, y: 12, width: (view.bounds.width-28)/2, height: 20))
        phoneNoTextField.placeholder = "你常用的联系电话"
        phoneNoTextField.textAlignment = .Right
        phoneNoTextField.keyboardType = .PhonePad
        
        phoneNoTextField.tag = PHONE_NO_INPUT_ID
        phoneNoTextField.addTarget(self, action: #selector(AdressAddViewController.scrollUpTextField(_:)), forControlEvents: .EditingDidBegin)
        
        defaultAddressSwitch = UISwitch(frame: CGRect(x: view.bounds.width-64, y: 8, width: 0, height: 0))
        if currentIndex == 0 {
            defaultAddressSwitch.on = true
        }
        if localAddress.count == 0{
            defaultAddressSwitch.enabled = false
        }
        
        if currentAddress.count != 0{
            
            locateData = [currentAddress.objectForKey("province") as! String, currentAddress.objectForKey("city") as! String, currentAddress.objectForKey("precinct") as! String]
            
            areaLabel.text = "\(locateData[0]) \(locateData[1]) \(locateData[2])"
            
            specifyTextField.text = currentAddress.objectForKey("specify") as? String
            
            receiverTextField.text = currentAddress.objectForKey("receiver") as? String
            
            phoneNoTextField.text = currentAddress.objectForKey("phone") as? String
            
        }
        
        areaSetView = UIControl(frame: view.frame)
        areaSetView.backgroundColor = UIColor(white: 0, alpha: 0.6)
        view.addSubview(areaSetView)
        areaSetView.alpha = 0
        areaSetView.addTarget(self, action: #selector(AdressAddViewController.closeAreaView), forControlEvents: .TouchDown)
        
        areaPicker = UIPickerView(frame: CGRect(x: 0, y: view.bounds.height - 200, width: view.bounds.width, height: 200))
        areaPicker.delegate = self
        areaPicker.dataSource = self
        areaPicker.backgroundColor = UIColor.whiteColor()
        areaPicker.autoresizingMask = .FlexibleWidth
        areaSetView.addSubview(areaPicker)
        
        areaConfirmBtn = UIButton(type: .System)
        areaConfirmBtn.setTitle("完成", forState: .Normal)
        areaConfirmBtn.frame = CGRect(x: view.bounds.width - 48, y: view.bounds.height - 192, width: 48, height: 20)
        areaConfirmBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        areaSetView.addSubview(areaConfirmBtn)
        areaConfirmBtn.addTarget(self, action: #selector(AdressAddViewController.closeAreaView), forControlEvents: .TouchUpInside)
        
        locateBtn = UILabel()
        locateBtn.text = "获取定位"
        areaSetView.addSubview(locateBtn)
        
        // TODO: 全局定位，获取到道路
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 2 {
            return 64
        }
        return 44
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "detail")
        
        if indexPath.row > 0 {
            let textLabel = UILabel(frame: CGRect(x: 16, y: 8, width: (view.bounds.width-36)/2, height: 28))
            cell.addSubview(textLabel)
            
            
            textLabel.text = INFO_KEY_CN[indexPath.row-1]
        }else{
            locateBtn.frame = CGRect(x: 16, y: 8, width: (view.bounds.width-36)/2, height: 28)
            cell.addSubview(locateBtn)
        }
        
        
        switch indexPath.row {
        case 1:
            
            
            cell.addSubview(areaLabel)
            cell.accessoryType = .DisclosureIndicator
            break
        case 2:
            
            
            cell.addSubview(specifyTextField)
            break
        case 3:
            
            cell.addSubview(receiverTextField)
            
            break
        case 4:
            cell.addSubview(phoneNoTextField)
            
            break
        case 5:
            
            cell.addSubview(defaultAddressSwitch)
            
            break
        default:
            break
        }
        
        
        
        
        return cell
    }

    func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        if indexPath.row == 0{
            return indexPath
        }
        if indexPath.row == 1{
            return indexPath
        }
        return nil
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.row == 0{
            getLocation()
        }
        if indexPath.row == 1{
            // MARK: 弹出地区选择
            areaSetView.alpha = 1
            self.areaSetView.backgroundColor = UIColor(white: 0, alpha: 0)
            self.areaPicker.center.y += 200
            self.areaConfirmBtn.center.y += 200
            UIView.animateWithDuration(0.3, animations: {
                self.areaSetView.backgroundColor = UIColor(white: 0, alpha: 0.6)
                self.areaPicker.center.y -= 200
                self.areaConfirmBtn.center.y -= 200
            })
        }
    }
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 3
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0:
            return locatePlistInfo.count
        case 1:
            let subDic = locatePlistInfo.objectAtIndex(pickerPosition[0]) as! NSDictionary
            let subAry = subDic.objectForKey("sub") as! NSArray
            
            return subAry.count
        case 2:
            let subDic = locatePlistInfo.objectAtIndex(pickerPosition[0]) as! NSDictionary
            let subAry = subDic.objectForKey("sub") as! NSArray
            let thirdDic = subAry.objectAtIndex(pickerPosition[1]) as! NSDictionary
            let thirdAry = thirdDic.objectForKey("sub") as! NSArray
            
            return thirdAry.count
        default:
            return 0
        }
        
    }
    
    func titleForRow(row: Int, forComponent component: Int) -> String? {
        // MARK:改成view形式，字体调小
        switch component {
        case 0:
            let areaDic = locatePlistInfo.objectAtIndex(row) as! NSDictionary
            
            return areaDic.objectForKey("name") as? String
        case 1:
            let subDic = locatePlistInfo.objectAtIndex(pickerPosition[0]) as! NSDictionary
            let subAry = subDic.objectForKey("sub") as! NSArray
            let areaDic = subAry.objectAtIndex(row) as! NSDictionary
            return areaDic.objectForKey("name") as? String
        case 2:
            let subDic = locatePlistInfo.objectAtIndex(pickerPosition[0]) as! NSDictionary
            let subAry = subDic.objectForKey("sub") as! NSArray
            let thirdDic = subAry.objectAtIndex(pickerPosition[1]) as! NSDictionary
            let thirdAry = thirdDic.objectForKey("sub") as! NSArray
            
            
            return thirdAry.objectAtIndex(row) as? String
        default:
            return nil
        }
    }
    
    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
        let view = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 48))
        view.textAlignment = .Center
        view.font = UIFont.systemFontOfSize(16)
        let text:String? = titleForRow(row, forComponent: component)
        view.numberOfLines = 0
        view.text = text
        return view
        
    }
    func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 48
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // MARK:sub 从0开始
        pickerPosition[component] = row
        if component == 0{
            pickerPosition[1] = 0
            pickerPosition[2] = 0
        }
        if component == 1{
            pickerPosition[2] = 0
        }
        
        pickerView.reloadAllComponents()
        for i in 0..<self.pickerPosition.count{
            self.areaPicker.selectRow(self.pickerPosition[i], inComponent: i, animated: true)
        }
    }

    func closeAreaView(){
        // MARK: 完成地区选择
        
        
        UIView.animateWithDuration(0.3, animations: { 
            self.areaSetView.backgroundColor = UIColor(white: 0, alpha: 0)
            self.areaPicker.center.y += 200
            self.areaConfirmBtn.center.y += 200
            }) { (finished) in
                self.areaSetView.backgroundColor = UIColor(white: 0, alpha: 0.6)
                self.areaPicker.center.y -= 200
                self.areaConfirmBtn.center.y -= 200
                self.areaSetView.alpha = 0
        }
        
        let subDic = locatePlistInfo.objectAtIndex(pickerPosition[0]) as! NSDictionary
        let subAry = subDic.objectForKey("sub") as! NSArray
        let thirdDic = subAry.objectAtIndex(pickerPosition[1]) as! NSDictionary
        let thirdAry = thirdDic.objectForKey("sub") as! NSArray
        
        var province = subDic.objectForKey("name") as! String
        var subLocal = ""
        if thirdAry.count != 0{
            subLocal = thirdAry.objectAtIndex(pickerPosition[2]) as! String
        }
        locateData = [province, thirdDic.objectForKey("name") as! String, subLocal]
        if province == "北京市" || province == "天津市" || province == "上海市" || province == "重庆市"{
            province = ""
        }
        
        areaLabel.text = "\(province)\(thirdDic.objectForKey("name") as! String)\(subLocal)"
        
        
    }
    func scrollUpTextField(sender: UITextField){
        switch sender.tag {
        case RECEIVER_INPUT_ID:
            if tableView.contentOffset.y < 24{
                tableView.setContentOffset(CGPoint(x: 0, y: 24), animated: true)
            }
            break
        case PHONE_NO_INPUT_ID:
            if tableView.contentOffset.y < 68{
                tableView.setContentOffset(CGPoint(x: 0, y: 68), animated: true)
            }
            break
        default:
            break
        }
    }
    func saveAddress(){
        // MARK: 保存地址
        if areaLabel.text == "" {
            UIAlertView(title: "请选择地区", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
            return
        }
        if specifyTextField.text == "" {
            UIAlertView(title: "请填写详细地址", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
            return
        }
        if receiverTextField.text == "" {
            UIAlertView(title: "请填写收件人", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
            return
        }
        if phoneNoTextField.text == "" {
            UIAlertView(title: "请填写联系电话", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
            return
        }
        currentAddress.setObject(locateData[0], forKey: "province")
        currentAddress.setObject(locateData[1], forKey: "city")
        currentAddress.setObject(locateData[2], forKey: "precinct")
        currentAddress.setObject(specifyTextField.text!, forKey: "specify")
        currentAddress.setObject(receiverTextField.text!, forKey: "receiver")
        currentAddress.setObject(phoneNoTextField.text!, forKey: "phone")
        
        
        if currentIndex >= localAddress.count{
            localAddress.addObject(currentAddress)
        }else{
            localAddress.replaceObjectAtIndex(currentIndex, withObject: currentAddress)
            
        }
        if defaultAddressSwitch.on {
            if currentIndex != 0{
                localAddress.removeObjectAtIndex(currentIndex)
                localAddress.insertObject(currentAddress, atIndex: 0)
            }
        }
        localAddress.writeToFile("\(DOCUMENT_PATH)/address.plist", atomically: true)
        navigationController?.popViewControllerAnimated(true)
    }
    
    func getLocation(){
        if !locating {
            if CLLocationManager.locationServicesEnabled(){
                locateMan = CLLocationManager()
                locateMan.delegate = self
                locateMan.requestWhenInUseAuthorization()
                locateMan.startUpdatingLocation()
                locateBtn.text = "正在获取定位"
                locating = true
            }else{
                UIAlertView(title: "定位不可用", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
            }
        }
        
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(locations.last!) { (clps:[CLPlacemark]?, err:NSError?) in
            manager.stopUpdatingLocation()
            var province:String?
            var city:String?
            var precinct:String?
            if err == nil{
                
                if clps?.count > 0{
                    province = clps?.last!.administrativeArea
                    city = clps?.last!.locality
                    precinct = clps?.last!.subLocality
                    print("\(province!) \(city!) \(precinct!)")
                    
                    var provItem = self.locatePlistInfo.objectAtIndex(0) as! NSDictionary
                    for i in 0..<self.locatePlistInfo.count{
                        
                        
                        if provItem.objectForKey("name") as! String == province! {
                            self.pickerPosition[0] = i
                            break
                        }
                        provItem = self.locatePlistInfo.objectAtIndex(i+1) as! NSDictionary
                    }
                    let subAry = provItem.objectForKey("sub") as! NSArray
                    var cityItem = subAry.objectAtIndex(0) as! NSDictionary
                    for j in 0..<subAry.count{
                        
                        
                        if cityItem.objectForKey("name") as! String == city! {
                            self.pickerPosition[1] = j
                            break
                        }
                        cityItem = subAry.objectAtIndex(j+1) as! NSDictionary
                    }
                    let thirdAry = cityItem.objectForKey("sub") as! NSArray
                    for k in 0..<thirdAry.count{
                        let areaStr = thirdAry.objectAtIndex(k) as! String
                        if areaStr == precinct! {
                            self.pickerPosition[2] = k
                            break
                        }
                    }
                    print(self.pickerPosition)
                    self.areaPicker.reloadAllComponents()
                    for i in 0..<self.pickerPosition.count{
                        self.areaPicker.selectRow(self.pickerPosition[i], inComponent: i, animated: true)
                    }
                    
                    self.locateData = [province!, city!, precinct!]
                    if province == "北京市" || province == "天津市" || province == "上海市" || province == "重庆市"{
                        province = ""
                    }
                    
                    self.areaLabel.text = "\(province!)\(city!)\(precinct!)"
                    //self.specifyTextField.placeholder = clps?.first!.thoroughfare
                    self.locateBtn.text = "获取定位"
                    self.locating = false
                }
                
                
            }else{
                self.locateBtn.text = "定位失败，点击重试"
                self.locating = false
            }
            
            
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
